<?php

namespace app\cash\model;
use app\common\model\CommonModel;
use think\facade\Db;


class OpenTableModel extends CommonModel{

    protected  $name = 'beautiful_open_table';

    protected  $pk   = 'open_table_id';
    /**
     * 模型写入前事件（钩子函数）
     */
    public static function onBeforeInsert($model)
    {
        $model->set("add_time", date('Y-m-d H:i:s'));
        $model->set("add_ip", request()->ip());
    }
    public static function getById($where,$field='*')
    {
        $list = self::alias('o')
            ->join('beautiful_table_number t','o.table_number_id=t.id')
            ->join('beautiful_region r','t.region_id=r.id')
            ->where(['o.is_delete'=>0])
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['o.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['open_table_id']),function ($query) use ($where){
                $query->where(['o.open_table_id'=>$where['open_table_id']]);
            })
            ->when(isset($where['table_number_id']),function ($query) use ($where){
                $query->where(['o.table_number_id'=>$where['table_number_id']]);
            })
            ->when(isset($where['status']),function ($query) use ($where){
                $query->where(['o.status'=>$where['status']]);
            })
            ->field($field)
            ->find();
        if($list) $list = $list->toArray();
        return $list;
    }
    public static function up($data,$where)
    {
        return self::update($data,$where);
    }
    public static function list($where,$order=[],$field='*',$page=0,$limit=0){
        $query = self::alias('o')
            ->join('beautiful_table_number n','n.id=o.table_number_id')
            ->join('beautiful_region r','n.region_id=r.id')
            ->field($field)
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['o.shop_id'=>$where['shop_id']]);
            })->when(isset($where['open_table_ids']),function ($query) use ($where){
                $query->whereIn('o.open_table_id',$where['open_table_ids']);
            })->when(isset($where['is_delete']),function ($query) use ($where){
                $query->where(['o.is_delete'=>$where['is_delete']]);
            });

        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->select()->toArray();
        $olist = [];
        if($list){
            foreach ($list as $k=>$v){
                $olist[$v['region_id']]['region_name'] = $v['region_name'];
                $olist[$v['region_id']]['table_name'][] = $v['table_name'];
            }
        }
        return compact('count','list','olist');
    }
}

